package com.fyx.timedTask;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fyx.config.FiveMongoConfig;
import com.fyx.config.RequestConfig;
import com.fyx.entity.*;
import com.fyx.mapper.LostGoldMapper;
import com.fyx.mapper.SysDictDetailMapper;
import com.fyx.mapper.UserDataByDateEntityMapper;
import com.fyx.until.DateUtil;
import com.fyx.until.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.persistence.criteria.Order;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Component(value="MailTask")
public class MailTask {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Resource(name = FiveMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate fiveMongoTemplate;


    @Autowired
    private SysDictDetailMapper sysDictDetailMapper;

    @Autowired
    private LostGoldMapper lostGoldMapper;

    @Autowired
    private UserDataByDateEntityMapper userDataByDateEntityMapper;

    public void runData(){
        UserEntity userEntity;
        Map map; List list1;
        Criteria criteria=new Criteria();
        criteria.and("time_end").gte(1672502400).lt(1689436800);
        criteria.and("platform").is("xunguangpay");
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("pid").sum("total_fee").as("totalFee").count().as("totalNum").max("time_end").as("lastFeeTime").last("pid").as("pid"),
                Aggregation.match(new Criteria("totalFee").gte(10000))
        );
        AggregationResults<UserDataByDateEntity> ar = mongoTemplate.aggregate(aggregation, "order", UserDataByDateEntity.class);
        List<UserDataByDateEntity> list = ar.getMappedResults();
        if(list.size()>0){
            for (UserDataByDateEntity userDataByDateEntity:list){

                criteria=new Criteria();
                criteria.and("pid").is(userDataByDateEntity.getPid());
                 aggregation = Aggregation.newAggregation(
                        Aggregation.match(criteria),
                        Aggregation.group().min("time_end").as("firstFeeTime")
                );
                ar = mongoTemplate.aggregate(aggregation, "order", UserDataByDateEntity.class);
                List<UserDataByDateEntity> list2 = ar.getMappedResults();
                if(list2.size()>0){
                    userDataByDateEntity.setFirstFeeTime(list2.get(0).getFirstFeeTime());
                }

                userDataByDateEntity.setId(null);
                criteria = new Criteria();
                criteria.and("pid").is(userDataByDateEntity.getPid());
                criteria.and("time_end").is(userDataByDateEntity.getFirstFeeTime());
                OrderEntity order=mongoTemplate.findOne(new Query().addCriteria(criteria),OrderEntity.class,"order");

               if(order!=null){
                    userDataByDateEntity.setFirstFee( order.getTotal_fee());
                }
                criteria = new Criteria();
                criteria.and("pid").is(userDataByDateEntity.getPid());
                criteria.and("time_end").is(userDataByDateEntity.getLastFeeTime());
                OrderEntity order1=mongoTemplate.findOne(new Query().addCriteria(criteria),OrderEntity.class,"order");
                if(order1!=null){
                    userDataByDateEntity.setLastFee( order1.getTotal_fee());
                }
                criteria = new Criteria();
                criteria.and("pid").is(userDataByDateEntity.getPid());
                criteria.and("mall_id").is(500330);
                order=null;
                order=mongoTemplate.findOne(new Query().addCriteria(criteria),OrderEntity.class,"order");
                if(order==null){
                    userDataByDateEntity.setHong( 0);
                }else {
                    userDataByDateEntity.setHong(1);
                }
                criteria = new Criteria();
                criteria.and("pid").is(userDataByDateEntity.getPid());
                criteria.and("mall_id").in(new Object[]{502112,502112,502112});
                List<OrderEntity> orderlist=mongoTemplate.find(new Query().addCriteria(criteria),OrderEntity.class,"order");
                if(orderlist.size()>0){
                    userDataByDateEntity.setMonthCard( orderlist.size());
                }else {
                    userDataByDateEntity.setMonthCard(0);
                }
                criteria=new Criteria();
                criteria.and("userid").is(userDataByDateEntity.getPid());
                userEntity=null;
                userEntity=mongoTemplate.findOne(new Query().addCriteria(criteria),UserEntity.class,"user");
                if(userEntity!=null){
                    userDataByDateEntity.setCreateTime(new Date().getTime()/1000);
                    userDataByDateEntity.setRegTime(userEntity.getReg_time());
                    userDataByDateEntity.setLastTime(userEntity.getLast_time());
                    String str = "{";
                    map=null; list1=null;
                    map = userEntity.getPlayinfo();
                    if(!map.get("gameTypec").toString().isEmpty()&&!map.get("gameTypec").toString().equals("{}")) {
                        list1 = (List) map.get("gameTypec");
                        if (list1.size() > 0) {
                            int i = 0;
                            for (Object o : list1) {
                                i++;
                                Map m = (Map) o;float j=0;
                                if((Integer)m.get("total")!=0){
                                    j=100*(Integer)m.get("winc")/ (Integer)m.get("total");
                                }
                                String res="";
                                if(i==1){ res="红中血流";}
                               else if(i==2){ res="名人堂";}
                                else if(i==3){ res="血流红中×6";}
                                else if(i==4){ res="红中血流接力";}
                                else if(i==5){ res="红包模式";}
                                else if(i==6){ res="不洗牌";}
                                else if(i==7){ res="比赛场";}
                                else if(i==8){ res="克隆玩法 ";}
                                else if(i==9){ res="雀神克隆 ";}
                                else if(i==10){ res="血流红中*8";}
                                else if(i==11){ res="现金赛";}
                                else if(i==12){ res="千层麻将";}
                                else{ res="八组杠";}
                                str += res + ":{total:" + m.get("total") + ",winc:" + m.get("winc") + ",win:"+j+"%},";
                            }
                        }
                    }
                    str+="}";
                    userDataByDateEntity.setGamesInfo(str);

                }
                System.out.println(userDataByDateEntity);
                userDataByDateEntityMapper.insert(userDataByDateEntity);
            }
        }
    }

    public void run(){
        long beginTime=DateUtil.getDayBegin().getTime()/1000;
        long nowTime=new Date().getTime()/1000;
        if((beginTime+3600)>nowTime){
            beginTime=DateUtil.getBeginDayOfYesterday().getTime()/1000;
        }
        String tableName=DateUtil.timeStamp2Date(beginTime+"","yyyyMM");;
        if(beginTime==nowTime){
            if(!DateUtil.timeStamp2Date(beginTime+"","yyyyMM").equals(DateUtil.timeStamp2Date(nowTime+"","yyyyMM"))){
                tableName =DateUtil.timeStamp2Date(beginTime+"","yyyyMM");
            }
        }
        long endTime=beginTime+86400;
        sendMail();
        sendClMail();
        nobleNums(beginTime);
        log.info("邮件信息统计：执行完毕=======================");
    }

    private  void sendMail(){
        Criteria criteria=new Criteria();
        criteria.and("anchor").is(true);
        criteria.and("anchors").is("anchor_12am_10");
        CheckListEntity  checkListEntity=mongoTemplate.findOne(new Query().addCriteria(criteria),CheckListEntity.class);
        if(checkListEntity==null){
            log.info("邮件完成执行完毕=======================");
        }else {
           String[] ids= checkListEntity.getUserid().split(",");
           for(int i=0;i<ids.length;i++){
               criteria=new Criteria();
               criteria.and("receiver").is(ids[i]);
               criteria.and("received").is(false);
               Long totals=mongoTemplate.count(new Query().addCriteria(criteria),"mail");
               QueryWrapper<SysDictDetail> wrapper1=new QueryWrapper<>();
               wrapper1.eq("dict_id",34);
               List<SysDictDetail> list1=sysDictDetailMapper.selectList(wrapper1);
               if(totals<Integer.parseInt(list1.get(0).getValue())){
                    for(int j=0;j<(Integer.parseInt(list1.get(0).getValue())-totals);j++){
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("p_id", ids[i]);
                        jsonObject.put("title", checkListEntity.getTitle());
                        jsonObject.put("content", checkListEntity.getContent());
                        jsonObject.put("mail_type", checkListEntity.getMail_stype());
                        jsonObject.put("award", checkListEntity.getAwards());
                        JSONObject map = new JSONObject();
                        map.put("cmd", "send_mail");
                        map.put("args", jsonObject);
                        try {
                            HttpUtil.post(RequestConfig.baseRequestUrl, map.toJSONString(), "utf-8");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
               }
           }
        }
    }
    private  void sendClMail(){
        Criteria criteria=new Criteria();
        criteria.and("anchor").is(true);
        criteria.and("anchors").is("anchor_12am_cl");
        CheckListEntity  checkListEntity=mongoTemplate.findOne(new Query().addCriteria(criteria),CheckListEntity.class);
        if(checkListEntity==null){
            log.info("邮件完成执行完毕=======================");
        }else {
            String[] ids= checkListEntity.getUserid().split(",");
            for(int i=0;i<ids.length;i++){
                criteria=new Criteria();
                criteria.and("receiver").is(ids[i]);
                criteria.and("received").is(false);
                Long totals=fiveMongoTemplate.count(new Query().addCriteria(criteria),"mail");
                QueryWrapper<SysDictDetail> wrapper1=new QueryWrapper<>();
                wrapper1.eq("dict_id",34);
                List<SysDictDetail> list1=sysDictDetailMapper.selectList(wrapper1);
                if(totals<Integer.parseInt(list1.get(0).getValue())){
                    for(int j=0;j<(Integer.parseInt(list1.get(0).getValue())-totals);j++){
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("p_id", ids[i]);
                        jsonObject.put("title", checkListEntity.getTitle());
                        jsonObject.put("content", checkListEntity.getContent());
                        jsonObject.put("mail_type", checkListEntity.getMail_stype());
                        jsonObject.put("award", checkListEntity.getAwards());
                        JSONObject map = new JSONObject();
                        map.put("cmd", "send_mail");
                        map.put("args", jsonObject);
                        try {
                            HttpUtil.post(RequestConfig.baseRequestUrl2, map.toJSONString(), "utf-8");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    private void nobleNums(Long beginTime){
        Criteria criteria=new Criteria();
        QueryWrapper<SysDictDetail> wrapper=new QueryWrapper<>();
        wrapper.eq("dict_id",33);
        List<SysDictDetail> listSysDictDetail=sysDictDetailMapper.selectList(wrapper);
        String result="";
        QueryWrapper<SysDictDetail> wrapper1=new QueryWrapper<>();
        wrapper1.eq("dict_id",16);
        wrapper1.eq("dict_sort",900);
        wrapper1.orderByDesc("dict_sort");
        List<SysDictDetail> list1=sysDictDetailMapper.selectList(wrapper1);
        SysDictDetail sysDictDetail1=new SysDictDetail();
        sysDictDetail1.setValue("total");
        sysDictDetail1.setDictSort(99);
        list1.add(sysDictDetail1);
        if(list1.size()>0) {
            for (SysDictDetail sysDictDetail2 : list1) {
                if (listSysDictDetail.size() > 0) {
                    for (SysDictDetail sysDictDetail : listSysDictDetail) {
                        criteria = new Criteria();
                        criteria.and("noble.level").is(Integer.parseInt(sysDictDetail.getLabel()));
                        if (sysDictDetail2.getValue() != "total") {
                            criteria.and("channel").regex(sysDictDetail2.getValue().split("_")[0]);
                        }
                        result += mongoTemplate.count(new Query().addCriteria(criteria), "user") + "@";
                    }
                }
                LostGold lostGold = new LostGold();
                lostGold.setTime(Long.valueOf(beginTime).intValue());
                lostGold.setChannel(sysDictDetail2.getValue());
                lostGold.setLostGold(result);
                lostGold.setFlag("nobleVip");
                result="";
                QueryWrapper<LostGold> wrapper3 = new QueryWrapper<>();
                wrapper3.eq("time", beginTime);
                wrapper3.eq("channel", sysDictDetail2.getValue());
                wrapper3.eq("flag","nobleVip");
                LostGold lostGold1 = lostGoldMapper.selectOne(wrapper3);
                if (lostGold1 == null) {
                    lostGoldMapper.insert(lostGold);
                } else {
                    lostGoldMapper.update(lostGold, wrapper3);
                }
            }
        }
    }
}
